﻿using LbangCMS.EFModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;
using System.Data.SqlClient;

namespace LbangCMS.DBService
{
    public class MemberService
    {
        private SqlConnection GetConnection()
        {
            return new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
        }

        public bool MobileIsExist(string mobile)
        {
            using (var db = new Database())
            {
                var member = db.Members.Where(o => o.Mobile == mobile).FirstOrDefault();
                if (member == null)
                    return false;
                return true;
            }
        }

        public int CreateMember(string mobile,string nick, string avatar, string openId, int agentId)
        {
            using (var conn = GetConnection())
            {
                var sql = "insert into Member(AgentId,Mobile,Avatar,Nick,OpenId) output inserted.Id values(@AgentId,@Mobile,@Avatar,@Nick,@OpenId)";
                return conn.Query<int>(sql, new { AgentId=agentId, Mobile=mobile, Avatar=avatar, Nick=nick, OpenId=openId }).FirstOrDefault();
            }
        }

        public Member GetMemberByMobile(string mobile)
        {
            using (var db = new Database())
            {
                var member = db.Members.Where(o => o.Mobile == mobile).FirstOrDefault();
                return member;
            }
        }

        public Member GetMemberByOpenId(string openId)
        {
            using (var db = new Database())
            {
                var member = db.Members.Where(o => o.OpenId == openId).FirstOrDefault();
                return member;
            }
        }

        public bool CreateSmsCode(string mobile,out string code)
        {
            code = new Random().Next(10000, 99999).ToString();
            using (var db = new Database())
            {
                var smsCode = new SmsCode()
                {
                    Mobile=mobile,
                    Code=code,
                    CreateTime=DateTime.Now
                };
                db.SmsCodes.Add(smsCode);
                db.SaveChanges();
                return true;
            }
        }

        public SmsCode GetLastSmsCode(string mobile)
        {
            using (var db = new Database())
            {
                return db.SmsCodes.Where(o => o.Mobile == mobile).OrderByDescending(o => o.ID).FirstOrDefault();
            }
        }
    }
}